﻿using SuperMap.Data;
using SuperMap.Data.Processing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ArcMapCache2SupermapCache
{
    class Program
    {
        static void Main(string[] args)
        {

            ArcMapXMLReader xmlreader = new ArcMapXMLReader();
           
            String path = "";

            if (args.Length >= 1)
            {
                path = args[0]; //@"D:\task\ArcGIS缓存数据\ArcGIS缓存数据\Layers7_11\conf.xml";
            }
            else
            {
                Console.WriteLine("请指定文件");
                Console.Read();
                return;
            }


            if (!File.Exists(path))
            {
                Console.WriteLine("对应配置文件不存在！");
                Console.Read();
                return;
            }

            Console.WriteLine("开始转换请稍等..........");

            xmlreader.Open(path);

            CacheWriter supermapCacheWriter = new CacheWriter();

            supermapCacheWriter.CacheName = "arcmap缓存";

            supermapCacheWriter.TileFormat = xmlreader.CacheTileFormat;

            supermapCacheWriter.TileCompress = xmlreader.CompressionQuality;

            Rectangle2D indexbounds = new Rectangle2D(xmlreader.TileOriginX, -xmlreader.TileOriginY, -xmlreader.TileOriginX, xmlreader.TileOriginY);

            supermapCacheWriter.IndexBounds = indexbounds;

            supermapCacheWriter.CacheBounds = xmlreader.CacheBounds;

            supermapCacheWriter.DPI = xmlreader.TileDPI;

            TileSize size;
            if (xmlreader.TileCols == 64)
            {
                size = TileSize.Size64;
            }
            else if (xmlreader.TileCols == 128)
            {
                size = TileSize.Size128;
            }
            else if (xmlreader.TileCols == 256)
            {
                size = TileSize.Size256;
            }
            else if (xmlreader.TileCols == 512)
            {
                size = TileSize.Size512;
            }
            else if (xmlreader.TileCols == 1024)
            {
                size = TileSize.Size1024;
            } 
            else 
            {
                size = TileSize.Size128;
            }
            supermapCacheWriter.TileSize = size;

            supermapCacheWriter.HashCode = "XXXXXXXXFIX";

            Dictionary<string, double> captionScales = xmlreader.CaptionCacheScales;

            //初始化各比例尺下的标题和比例尺
            supermapCacheWriter.CacheScaleCaptions.Clear();

            supermapCacheWriter.StorageType = StorageType.Original;
           
            foreach (Double scale in captionScales.Values)
            {
                if (!supermapCacheWriter.CacheScaleCaptions.ContainsKey(scale))
                {
                    supermapCacheWriter.CacheScaleCaptions.Add(scale, ((Int32)(1 / scale)).ToString());
                }
            }

            string tempfilePath = "./.tempWKT";
            if (File.Exists(tempfilePath))
                File.Delete(tempfilePath);
            StreamWriter streamWriter = File.CreateText(tempfilePath);
            streamWriter.WriteLine(xmlreader.WKT);
            streamWriter.Flush();

            PrjCoordSys prj = new PrjCoordSys();
            prj.FromFile(tempfilePath,PrjFileType.Esri);

            supermapCacheWriter.PrjCoordSys = prj;

            exchangetile(supermapCacheWriter, xmlreader);

            Console.WriteLine("........结束........");
        }

        static void exchangetile(CacheWriter supermapCacheWriter,ArcMapXMLReader arcmapReader)
        {
            String path = arcmapReader.FilePath;

            string dictionary = Path.GetDirectoryName(path);

            String tempSupermapCachePath = dictionary + "/supermapCache";

            string NowCachePath = tempSupermapCachePath + DateTime.Now.ToString("HH-mm-ss");
            Directory.CreateDirectory(NowCachePath);
            supermapCacheWriter.OutputFolder = NowCachePath;
            if (supermapCacheWriter.ToConfigFile(NowCachePath + "/" + supermapCacheWriter.CacheName + "/supermapCache.sci"))
            {
                Console.WriteLine("转换为sci文件成功.......");
            }
            else
            {
                Console.WriteLine("转换sci文件失败.......");
                Console.WriteLine("任意键结束");
                Console.Read();
               
                return;
            }

            Console.WriteLine("开始转换对应文件夹文件.......");

            Directory.CreateDirectory(NowCachePath);

            string[] directories = Directory.GetDirectories(dictionary + "\\_alllayers");

            //arcmap缓存的不同等级
            foreach (string tilepath in directories)
            {
                string[] ranksDirectories = Directory.GetDirectories(tilepath);
                
                //不同等级中的不同行号的文件夹
                foreach(string ranksDir in ranksDirectories)
                {
                    string[] columFiles = Directory.GetFiles(ranksDir);

                    DirectoryInfo info = Directory.GetParent(ranksDir);

                    string arcLevelDirName = info.Name;
                    string superCaptionDirName;
                    
                    double scale;
                    if (arcmapReader.CaptionCacheScales.TryGetValue(arcLevelDirName, out scale))
                    {
                        supermapCacheWriter.CacheScaleCaptions.TryGetValue(scale, out superCaptionDirName);
                    }

                    int pozition = ranksDir.LastIndexOf('R');

                    string rank = ranksDir.Substring(pozition+1);

                    //不同行号文件夹中的图片文件
                    foreach(string columfile in columFiles)
                    {
                        int pos = columfile.LastIndexOf('.');
                        string colum = columfile.Substring(pos - 8, 8);

                        Int32 supermapCol = Convert.ToInt32(colum, 16);
                        Int32 supermapRow = Convert.ToInt32(rank, 16);
                        string superMapTilePath = supermapCacheWriter.GetLocalTilePath(scale, supermapRow, supermapCol);

                        Directory.CreateDirectory(Path.GetDirectoryName(superMapTilePath)); 

                        File.Copy(columfile, superMapTilePath);

                        Console.WriteLine("拷贝文件:    " + columfile + " 到目录: " + superMapTilePath);

                    }

                }


            }

             Console.WriteLine("\n\n生成文件位于：" + NowCachePath);
        }
    }
}
